MVC model is basically a C# or VB.NET class. A model is accessible by both controller and view. A model can be used to pass data from controller to view. A view can use model to display data in page.Model objects are the parts of the application that implement the domain logic, also known as business logic. Domain logic handles the data that is passed between the database and the UI. For example, in an inventory system, the model keeps track of the items in storage and the logic to determine whether an item is in stock. In addition, the model would be the part of the application that updates the database when an item is sold and shipped out of the warehouse. Often, the model also stores and retrieves model state in a database.
We can add Model as depicted in a figure below:
Right Click on Model Folder Add a Class.
After selecting Class option, change the class name if you want. Here I change it into ModelClass.cs
Then click on Add button.
After adding a class, you must also have to know the functionality of that class. In Model class we can implements properties, methods and validations attribute etc. according to our need. We can perform all the programming operation in the Class as we did earlier in various programming languages.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace FisrtMVCApp.Models
{
publicclassModelClass
{
[Required(ErrorMessage="First Name Required:")]
[DisplayName("Enter First Name:")]
[StringLength(30, ErrorMessage = ":Less than 30 characters")]
[RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage = "Special Characters
not allowed"
not allowed")]
publicstring FirstName
{
get;
set;
}
[Required(ErrorMessage = "First Name Required:")]
[DisplayName("Enter Last Name:")]
[StringLength(30, ErrorMessage = ":Less than 30 characters")]
[RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage = "Special Characters not allowed"
not allowed")]
publicstring LastName
{
get;
set;
}
publicbool IsExist()
{
returnfalse;
}
}
By creating above Model class, we can understand and can easily implement the functionality of Model in MVC ASP.NET.
Leave Comment